package com.sxj.springsourcecode.springframework.factory.support;

import com.sxj.springsourcecode.springframework.factory.config.BeanDefinition;
import com.sxj.springsourcecode.springframework.factory.config.DisposableBean;
import com.sxj.springsourcecode.springframework.utils.ClassUtil;
import org.springframework.util.StringUtils;

/**
 * @ProjectName: spring-source-code
 * @Package: com.sxj.springsourcecode.springframework.factory.support
 * @ClassName: DisposableBeanAdapter
 * @Author: sxj
 * @Description:
 * @Date: 2024/2/22 23:36
 * @Version: 1.0.0
 */
public class DisposableBeanAdapter implements DisposableBean {
    private String beanName;
    private Object bean;
    private BeanDefinition beanDefinition;

    public DisposableBeanAdapter(String beanName, Object bean, BeanDefinition beanDefinition) {
        this.beanName = beanName;
        this.bean = bean;
        this.beanDefinition = beanDefinition;
    }

    @Override
    public void destroy() {
        if (bean instanceof DisposableBean){
            DisposableBean disposableBean = (DisposableBean) bean;
            disposableBean.destroy();
        }

        String destroyMethodName = beanDefinition.getDestroyMethodName();
        if (StringUtils.hasText(destroyMethodName) && !(bean instanceof DisposableBean && "destory".equals(destroyMethodName))){
            ClassUtil.invokeMethod(beanDefinition.getClz(),bean,destroyMethodName);
        }
    }
}
